import CryptoJS from 'crypto-js'
import { MutableRefObject } from 'react'

// 配置信息
const APPID = '0bc63f8f'
const API_SECRET = 'ZjcyYTgzY2U4YzA4MDBhNWMxMjVkMTAz'
const API_KEY = '97b9d6f86ce4832e9b0ca7b966d8ad14'
const AI_DOMAIN = 'patch' // 微调领域设置为 patch
const PATCH_ID = ['1826277589285523456'] // 传入实际的 patch_id
const SPARK_URL = 'wss://spark-api-n.xf-yun.com/v1.1/chat' // 替换为实际的 WebSocket URL

// 生成WebSocket URL的函数
const getWebsocketUrl = (): Promise<string> => {
  return new Promise<string>((resolve) => {
    const host = new URL(SPARK_URL).host
    const path = new URL(SPARK_URL).pathname
    const date = new Date().toUTCString()
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${path} HTTP/1.1`
    const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, CryptoJS.enc.Utf8.parse(API_SECRET))
    const signature = CryptoJS.enc.Base64.stringify(signatureSha)
    const authorizationOrigin = `api_key="${API_KEY}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`
    const authorization = btoa(authorizationOrigin)

    const url = `${SPARK_URL}?authorization=${authorization}&date=${date}&host=${host}`
    resolve(url)
  })
}

// 封装的对话函数
const dialogue = (
  question: string,
  ttsWSRef: MutableRefObject<WebSocket | null>,
  totalResRef: MutableRefObject<string>,
  dataRefresh: () => void,
  endofJudgment?: (data: boolean) => void,
) => {
  getWebsocketUrl().then((url) => {
    if ('WebSocket' in window) {
      ttsWSRef.current = new WebSocket(url)
    } else {
      alert('浏览器不支持WebSocket')
      return
    }

    const webSocketSend = () => {
      const params = {
        header: {
          app_id: APPID,
          patch_id: PATCH_ID, // 添加 patch_id 参数
        },
        parameter: {
          chat: {
            domain: AI_DOMAIN,
            temperature: 0.5,
            max_tokens: 2048,
          },
        },
        payload: {
          message: {
            text: [
              {
                role: 'user',
                content: question,
              },
            ],
          },
        },
      }
      ttsWSRef.current?.send(JSON.stringify(params))
    }

    const result = (resultData: string) => {
      try {
        const jsonData = JSON.parse(resultData)
        const content = jsonData.payload?.choices?.text[0]?.content || ''
        totalResRef.current += content

        dataRefresh()

        if (jsonData.header.code !== 0) {
          console.error(`${jsonData.header.code}: ${jsonData.header.message}`)
          return
        }

        if (jsonData.header.code === 0 && jsonData.header.status === 2) {
          ttsWSRef.current?.close()
        }
      } catch (error) {
        console.error('解析响应数据时出错:', error)
      }
    }

    if (ttsWSRef.current) {
      ttsWSRef.current.onopen = () => {
        if (endofJudgment) {
          endofJudgment(false)
        }
        webSocketSend()
      }
      ttsWSRef.current.onmessage = (e: MessageEvent) => {
        result(e.data)
      }
      ttsWSRef.current.onerror = (error) => {
        console.error('WebSocket Error:', error)
        ttsWSRef.current?.close()
      }
      ttsWSRef.current.onclose = () => {
        if (endofJudgment) {
          endofJudgment(true)
        }
      }
    }
  })
}

export default dialogue
